package mysqldb

import (
	"gorm.io/gorm"
	"time"
)

type MonMysqlPlugin struct {
	DBName string
}

func (p MonMysqlPlugin) Name() string {
	return "mysqlMonPlugin"
}

func (p MonMysqlPlugin) Initialize(db *gorm.DB) error {
	_ = db.Callback().Create().Before("gorm:before_create").Register("monCallBackBeforeCreate", before)
	_ = db.Callback().Query().Before("gorm:query").Register("monCallBackBeforeQuery", before)
	_ = db.Callback().Delete().Before("gorm:before_delete").Register("monCallBackBeforeDelete", before)
	_ = db.Callback().Update().Before("gorm:setup_reflect_value").Register("monCallBackBeforeUpdate", before)
	_ = db.Callback().Row().Before("gorm:row").Register("monCallBackBeforeRow", before)
	_ = db.Callback().Raw().Before("gorm:raw").Register("monCallBackBeforeRaw", before)

	// 结束后
	_ = db.Callback().Create().After("gorm:after_create").Register("monCallBackAfterCreate", getAfter(p.DBName))
	_ = db.Callback().Query().After("gorm:after_query").Register("monCallBackAfterQuery", getAfter(p.DBName))
	_ = db.Callback().Delete().After("gorm:after_delete").Register("monCallBackAfterDelete", getAfter(p.DBName))
	_ = db.Callback().Update().After("gorm:after_update").Register("monCallBackAfterUpdate", getAfter(p.DBName))
	_ = db.Callback().Row().After("gorm:row").Register("monCallBackAfterRow", getAfter(p.DBName))
	_ = db.Callback().Raw().After("gorm:raw").Register("monCallBackAfterRaw", getAfter(p.DBName))
	return nil
}

func before(db *gorm.DB) {
	db.InstanceSet("start_time", time.Now())
}

func getAfter(dbName string) func(db *gorm.DB) {
	return func(db *gorm.DB) {
		_, isExist := db.InstanceGet("start_time")
		if !isExist {
			return
		}
	}
}
